'use strict'

const fs = require('fs');
const path = require("path");

const child_process = require('child_process');

const replaceStr = `
var jspb = require('google-protobuf');
var goog = jspb;
`
const replaceStr2 = `
var jspb = require('google-protobuf');
var goog = jspb;
goog.DEBUG=true;
var COMPILED=false;
`

const appendStr = `
    // var proto = {};
`
const lastappendStr = `
// if(window != null){
//     window.proto = proto;
// }
proto.jspb = jspb
exports.proto = proto;
`

function combineProto() {
    var totalProto = path.join(__dirname, "./protos/protos.proto");
    console.log("totalProto====", totalProto);
    var status = fs.existsSync(totalProto);
    if (status) {
        fs.unlinkSync(totalProto);
    }
    var filePath = './protos';
    //根据文件路径读取文件，返回文件列表  
    var files = fs.readdirSync(filePath);
    // var content = "syntax = 'proto3';\npackage plr;\n\n";
    var content = "syntax = 'proto3';\n\n\n";
    //遍历读取到的文件列表  
    console.log("files===", files);
    for (let index = 0; index < files.length; index++) {
        const filename = files[index];
        //获取当前文件的绝对路径  
        var filedir = path.join(filePath, filename);
        //根据文件路径获取文件信息，返回一个fs.Stats对象  
        var stats = fs.statSync(filedir);
        var isFile = stats.isFile();//是文件  
        if (isFile && filename.lastIndexOf('.proto') != -1) {
            console.log("combine file=====", filename);
            var tempContent = fs.readFileSync(filedir);
            content += tempContent;
        }
    }
    fs.writeFileSync(totalProto, content);
    console.log("合并proto end==");
    generalProtoJs();
}

function generalProtoJs() {
    var compilePath = "./bin/protoc"
    if (process.platform == "darwin") {
        compilePath += '-mac'
    } else {
        compilePath += '.exe'
    }
    compilePath = path.join(__dirname, compilePath);
    child_process.exec(compilePath + "  --js_out=import_style=commonjs,binary:. ./protos/protos.proto", (error, stdout, stderr) => {
        if (error) {
            console.log(error);
            return
        }
        let tempContent = fs.readFileSync('./protos/protos_pb.js').toString();
        tempContent = tempContent.replace(replaceStr, replaceStr2);
        // tempContent = appendStr + tempContent;
        tempContent = appendStr+tempContent+lastappendStr;
        fs.writeFileSync('./protos/protos_pb.js', tempContent);
        console.log("generalProtoJs end======");
        let cmdPath = path.join(__dirname, "./node_modules/.bin/webpack");
        // let cmdPath = path.join(__dirname, "./node_modules/.bin/browserify ./protos/exports.js > protolib.js");
        console.log(cmdPath);
        child_process.exec(cmdPath, function (error, stdout, stderr) {
            if (error) {
                console.log("打包错误", error);
                return
            }
            console.log("打包完成....", stdout);
        });
    });

}


combineProto();



